# -*- coding:utf-8 -*-
 
# date： 2020-5-30
# author： jingluo
from flask import Flask, render_template,request, session
import get_douban_databses
import sqlite3
import os

# 分词
import jieba
# 绘图，数据可视化
from matplotlib import pyplot as plt
# 词云
from wordcloud import WordCloud
# 图片处理
from PIL import Image
# 矩阵运算
import numpy as np

# 自定义template路径
app = Flask(__name__,template_folder="../templates/",
	static_folder='../static/') #应用

# flask的session需要用到的秘钥字符串
app.config["SECRET_KEY"] = "akjsdhkjashdkjhaksk120191101asd"

@app.route("/")
def index():
	try:
		with open('word_length.txt', 'r') as file:
			word_length = file.readline()
			session['word_length'] = word_length
			file.close()
	except:
		word_length = 5633
		session['word_length'] = word_length
	return render_template("template/home.html",word_length = word_length)

@app.route("/home")
def home():
	word_length = session.get('word_length')
	return render_template("template/home.html",word_length = word_length)

@app.route("/movie")
def movie():
	movies = []
	con = sqlite3.connect("movie.db")
	cur = con.cursor()
	sql = "select * from movie250"
	data = cur.execute(sql)
	for item in data:
		movies.append(item)
	cur.close()
	con.close()
	return render_template("template/movie.html",movies = movies)

@app.route("/score")
def score():
	score = []
	number = []
	con = sqlite3.connect("movie.db")
	cur = con.cursor()
	sql = "select score,count(score) from movie250 group by score"
	data = cur.execute(sql)
	for item in data:
		score.append(item[0])
		number.append(item[1])
	cur.close()
	con.close()
	return render_template("template/score.html", score = score, number = number)

# 生成词云图片
def makeWordCloud():
	# 准备词云所需的词
	con = sqlite3.connect('movie.db')
	cur = con.cursor()
	sql = 'select instroduction from movie250'
	data = cur.execute(sql)
	text = ""
	for item in data:
		text = text + item[0]
	cur.close()
	con.close()

	cut = jieba.cut(text)
	string = ' '.join(cut)

	filename = 'word_length.txt'
	with open(filename, 'w') as file:
		file.write(str(len(string)))
		file.close()

	img = Image.open(r'../static/assets/img/tree.jpg')
	img_arry = np.array(img) # 将图片转换成数组
	wc = WordCloud(
		background_color = 'white',
		mask = img_arry,
		font_path = 'STCAIYUN.TTF' # 字体锁在位置： C:\Windows\Fonts
		)
	wc.generate_from_text(string)

	# 绘制图片
	fig = plt.figure(1)
	plt.imshow(wc)
	plt.axis('off') # 是否显示坐标轴
	# plt.show() # 显示生成的词云图片

	# 输出词云图片到文件
	plt.savefig(r'../static/assets/img/word.jpg', dpi=800)
	plt.close()

@app.route("/word")
def word():
	return render_template("template/word.html")

@app.route("/team")
def team():
	return render_template("template/team.html")

if __name__ == '__main__':
	app.config.update(DEBUG=True)
	if not os.path.exists('movie.db'):
		get_douban_databses.main()
	if not os.path.exists('../static/assets/img/word.jpg'):
		makeWordCloud()
	app.run()